<template>
  <div class="users">
    <!-- 1、面包屑导航  -->
    <el-breadcrumb :separator-icon="ArrowRight">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 2、card -->
    <el-card>
      <!-- 2-1 搜索框和添加按钮 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            v-model="params.query"
            placeholder="输入用户名"
            clearable
            @clear="search()"
          >
            <!-- <template #prepend>
              <el-button :icon="Search" />
            </template> -->
            <template #append>
              <el-button :icon="Search" @click="search()" />
            </template>
          </el-input>
        </el-col>
        <el-col :span="2">
          <el-button type="primary" :icon="Plus" @click="showAddDialogVisible()"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
      <!-- 2-2 用户列表 -->
      <el-table
        :data="userList"
        border
        stripe
        fit
        :header-cell-style="header_cell_style"
        style="width: 100%"
      >
        <el-table-column type="index" label="序号" width="80" align="center" />
        <el-table-column prop="username" label="用户名" align="center" />
        <el-table-column prop="mobile" label="电话"  show-overflow-tooltip align="center" />
        <el-table-column prop="role_name" label="角色" align="center" />
        <el-table-column label="状态" align="center">
          <template v-slot="scope">
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#057b05"
              inactive-color="#F00"
              @change="updateUserMgState(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="email" label="邮箱" show-overflow-tooltip align="center" />
        <el-table-column label="操作" align="center" width="350">
          <template #default="scope">
            <el-button
              type="primary"
              :icon="EditPen"
              size="default"
              @click="showUpdateUserDialog(scope.row)"
              >修改</el-button
            >
            <el-button
              type="danger"
              :icon="Delete"
              size="default"
              @click="deleteUser(scope.row)"
              >删除</el-button
            >
            <el-button
              type="success"
              :icon="Setting"
              size="default"
              @click="showSetRoleDialog(scope.row)"
              >分配角色</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 2-3 分页器 -->
      <el-pagination
        :currentPage="params.pagenum"
        :page-size="params.pagesize"
        :page-sizes="[5, 10, 15, 20, 25, 30, 35, 40, 45, 50]"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>
    <!-- 3、修改用户对话框 -->
    <el-dialog
      v-model="updateUserVisble"
      title="修改用户"
      width="50%"
      draggable
      @close="reset(updateRef)"
    >
      <el-form
        ref="updateRef"
        :model="updateUser"
        :rules="rules"
        label-width="60px"
        size="large"
      >
        <el-form-item label="编号">
          <el-input v-model="updateUser.id" disabled />
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="updateUser.mobile" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="updateUser.email" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="submitUpdate(updateRef)">修改</el-button>
          <el-button type="primary" @click="updateUserVisble = false"
            >取消</el-button
          >
        </span>
      </template>
    </el-dialog>
    <!-- 4、添加用户对话框 -->
    <el-dialog
      v-model="addUserVisble"
      title="添加用户"
      width="50%"
      draggable
      @close="reset(addRef)"
    >
      <el-form
        ref="addRef"
        :model="addUser"
        :rules="rules"
        label-width="70px"
        size="large"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addUser.username" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addUser.password" type="password" />
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="addUser.mobile" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUser.email" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="submitAdd(addRef)">添加</el-button>
          <el-button type="primary" @click="addUserVisble = false"
            >取消</el-button
          >
        </span>
      </template>
    </el-dialog>
    <!-- 5、分配角色 -->
    <el-dialog v-model="setRoleVisble" title="分配角色" width="30%" draggable>
      <el-row>
        <el-col :span="4">当前用户</el-col>
        <el-col :span="20">{{ setRoleUser.username }}</el-col>
      </el-row>
      <el-row>
        <el-col :span="4">当前角色</el-col>
        <el-col :span="20">{{ setRoleUser.role_name }}</el-col>
      </el-row>
      <el-row>
        <el-col :span="4">选择角色</el-col>
        <el-col :span="20">
          <el-select
            v-model="setRoleUser.rid"
            style="width: 100%"
            placeholder="请选择角色"
          >
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            />
          </el-select>
        </el-col>
      </el-row>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="submitSetRole()">确认</el-button>
          <el-button type="primary" @click="setRoleVisble = false"
            >取消</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
/*---------------------- 引入资源 ---------------------- */
import { ref, reactive, onMounted } from "vue";
import {
  ArrowRight,
  Plus,
  Search,
  EditPen,
  Delete,
  Setting,
} from "@element-plus/icons-vue";
import { error, success, confirm, info, alert } from "@/utils/message";
import request from "@/utils/request";
/*---------------------- 定义变量 ---------------------- */
let total = ref(0), 
  userList = ref([]),
  header_cell_style = ref({
    backgroundColor: "#00A0ff",
    color: "#fff",
    textAlign: "center",
  }),
  params = reactive({
    query: "",
    pagenum: 1,
    pagesize: 5,
  }),
  updateUser = reactive({
    id: 0,
    email: "",
    mobile: "",
  }),
  updateUserVisble = ref(false), //控制修改用户对话框是否显示
  rules = reactive({
    username: [
      { required: true, message: "请输入用户名", trigger: "blur" },
      { min: 3, max: 12, message: "长度在 3 - 12 个字符", trigger: "blur" },
    ],
    password: [
      { required: true, message: "请输入密码", trigger: "blur" },
      { min: 6, max: 12, message: "长度在 6 - 12 个字符", trigger: "blur" },
    ],
    email: [
      { required: true, message: "请输入邮箱", trigger: "blur" },
      {
        validator: (r, v, c) => {
          r =
            /^\w+@([a-z]{2,}|\d{3,})(\.com|\.cn|\.com\.cn|\.org|\.net|\.edu)$/;
          if (!r.test(v)) {
            return c(new Error("非法的邮箱"));
          }
          c();
        },
        trigger: "blur",
      },
    ],
    mobile: [
      { required: true, message: "请输入电话号码", trigger: "blur" },
      {
        validator: (r, v, c) => {
          r = /^1[3456789]\d{9}$/;
          if (!r.test(v)) {
            return c(new Error("非法的电话号码"));
          }
          c();
        },
        trigger: "blur",
      },
    ],
  }),
  updateRef = ref(),
  addUserVisble = ref(false), //控制添加用户的对话框是否显示
  addUser = reactive({
    username: "",
    password: "",
    email: "",
    mobile: "",
  }),
  addRef = ref(),
  setRoleVisble = ref(false), //控制分配角色的对话框是否显示
  roleList = ref([]),
  setRoleUser = reactive({
    id: 0,
    username: "",
    role_name: "",
    rid: "",
  });
/*---------------------- 功能函数 ---------------------- */
//删除用户
function deleteUser(user) {
  let { role_name } = user;
  if (role_name === "超级管理员") {
    return alert("超级管理员不能删除");
  }
  confirm("确认要删除当前用户吗?", "删除用户", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      //点击确定后执行的函数
      let option = {
        url: `users/${user.id}`,
        type: "delete",
      };
      try {
        let { data: res } = await request(option);
        if (res.meta.status !== 200) {
          return error(res.meta.msg);
        }
        success(res.meta.msg);
        if (userList.length === 1 && params.pagenum !== 1) {
          params.pagenum--;
        }
        getUserList();
      } catch (err) {
        console.log(err);
      }
    })
    .catch(() => {
      //点击取消后执行的函数
      info("您取消了删除");
    });
}
// 给指定的用户分配角色
async function SetRole() {
  let option = {
    url: `users/${setRoleUser.id}/role`,
    type: "put",
    data: setRoleUser,
  };
  try {
    let { data: res } = await request(option);
    if (res.meta.status !== 200) {
      return error(res.meta.msg);
    }
    success(res.meta.msg);
    setRoleVisble.value = false;
    getUserList();
  } catch (error) {
    console.log(error);
  }
}
//提交分配角色
function submitSetRole() {
  if (setRoleUser.rid == "") {
    return error("请选择用户角色");
  }
  SetRole();
}
//请求所有角色信息
async function getRoleList() {
  let option = {
    url: "roles",
    type: "get",
  };
  try {
    let { data: res } = await request(option);
    if (res.meta.status !== 200) {
      return error(res.meta.msg);
    }
    roleList.value = res.data;
  } catch (error) {
    console.log(error);
  }
}
//点击显示分配权限对话框
function showSetRoleDialog(user) {
  setRoleUser.id = user.id;
  setRoleUser.username = user.username;
  setRoleUser.role_name = user.role_name;
  getRoleList();
  setRoleVisble.value = true;
}
//添加用户请求方法
async function addUserInfo() {
  let option = {
    type: "post",
    url: "users",
    data: addUser,
  };
  try {
    let { data: res } = await request(option);
    if (res.meta.status !== 201) {
      return error(res.meta.msg);
    }
    success(res.meta.msg);
    addUserVisble.value = false;
    getUserList();
  } catch (error) {
    console.log(error);
  }
}
//提交添加用户对话框
function submitAdd(form) {
  form.validate((v) => {
    if (!v) {
      return error("请正确填写用户信息");
    } else {
      addUserInfo();
    }
  });
}
//点击显示对话框
function showAddDialogVisible() {
  addUserVisble.value = true;
}
//执行修改用户信息
async function updateUserInfo() {
  //准备参数
  let option = {
    url: `users/${updateUser.id}`,
    type: "put",
    data: updateUser,
  };
  try {
    let { data: res } = await request(option);
    if (res.meta.status !== 200) {
      return error(res.meta.msg);
    }
    success(res.meta.msg);
    updateUserVisble.value = false;
    getUserList();
  } catch (err) {
    console.log(err);
  }
}
//提交表单
function submitUpdate(form) {
  form.validate((v) => {
    if (!v) {
      return error("请正确填写用户信息");
    } else {
      updateUserInfo();
    }
  });
}
// 重置表单
function reset(form) {
  form.resetFields();
}
//实现修改用户对话框
function showUpdateUserDialog(user) {
  for (const key in updateUser) {
    updateUser[key] = user[key];
  }
  updateUserVisble.value = true;
}
//点击查询
function search() {
  params.pagenum = 1;
  getUserList();
}
//修改用户状态的函数
async function updateUserMgState(user) {
  let options = {
    url: `users/${user.id}/state/${user.mg_state}`,
    type: "put",
  };
  try {
    let { data: res } = await request(options);
    if (res.meta.status !== 200) {
      return error(res.meta.msg);
    }
    success(res.meta.msg);
    user = res.data;
  } catch (err) {
    console.log(err);
  }
}
function handleSizeChange(size) {
  params.pagesize = size;
  params.pagenum = 1;
  getUserList();
}
function handleCurrentChange(num) {
  params.pagenum = num;
  getUserList();
}
async function getUserList() {
  let options = {
    url: "users",
    type: "get",
    data: params,
  };
  try {
    let { data: res } = await request(options);
    if (res.meta.status !== 200) {
      return error(res.meta.msg);
    }
    userList.value = res.data.users;
    total.value = res.data.total;
  } catch (err) {
    console.log(err);
  }
}
/*---------------------- 生命周期函数 ---------------------- */
onMounted(() => {
  getUserList();
});
</script>

<style lang="scss" scoped>
.el-card {
  margin: 10px 0;
}
.el-table {
  margin: 20px 0;
}
.el-pagination {
  float: right;
  margin-bottom: 15px;
}
.el-row {
  padding: 10px 0;
}
</style>